<template>
    <div class="settlement-pay">
        <div class="header-box">
            <div class="header-left">
                <div class="back">
                    <i class="el-icon-arrow-left" @click="backFun"></i>
                </div>
                <div class="title">结账</div>
            </div>
        </div>
        <div class="settlement-info">
            <div class="choice-box">
                <div class="choice-info">
                    <div class="choice-info-left">
                        <div class="img-box">
                            <img
                                :src="
                                    customerInfo.avatar
                                        ? customerInfo.avatar
                                        : require('../../static/images/Uimg.png')
                                "
                            />
                        </div>
                        <div class="choice-content">
                            <div class="title">
                                <span>
                                    {{
                                        customerInfo.name
                                            ? customerInfo.name
                                            : "请选择1个客户"
                                    }}</span
                                >
                                <span>{{
                                    customerInfo.company
                                        ? customerInfo.company
                                        : ""
                                }}</span>
                            </div>
                        </div>
                    </div>
                    <!-- <div class="choice-info-right">
                        <el-button size="mini" @click="selectCustom">{{
                            customerInfo.name ? "更换" : "选择客户"
                        }}</el-button>
                    </div> -->
                </div>
            </div>
            <div class="settlement-form">
                <el-form
                    :model="settlementForm"
                    :rules="rules"
                    ref="settlementForm"
                    label-width="80px"
                    class="demo-settlementForm"
                    hide-required-asterisk
                >
                    <el-form-item label="订单金额">
                        <span class="order-pic">{{ cartInfo.amount }}</span>
                        <span class="discount" v-if="cartInfo.discount > 0">{{
                            `(原价${cartInfo.amount_totle} 折扣${parseFloat(
                                cartInfo.discount_r
                            )}% 优惠${cartInfo.discount})`
                        }}</span>
                    </el-form-item>
                    <el-form-item label="实收金额" prop="amount_receive">
                        <el-input
                            v-model="settlementForm.amount_receive"
                            placeholder="请输入实收金额"
                            class="input-w"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="收款方式"
                        v-if="settlementForm.amount_receive > 0"
                        prop="payid"
                    >
                        <el-select
                            v-model="settlementForm.payid"
                            class="input-w"
                        >
                            <el-option
                                v-for="item in pay_ls"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="客户余额"
                        v-if="
                            settlementData.customerid > 0 &&
                            settlementData.money > 0
                        "
                    >
                        <div class="order-box">
                            <span class="order-pic">{{
                                settlementData.money
                            }}</span>
                            <el-switch
                                v-model="is_money"
                                active-color="#3388ff"
                                inactive-color="#dcdfe6"
                            >
                            </el-switch>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item
                        label="订单类型"
                    >
                        <div class="order-class-box">
                            <el-radio-group v-model="orderClass">
                                <el-radio  :label="1">门店单</el-radio>
                                <el-radio  :label="2">云店单</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item> -->
                    <el-form-item label="开单门店" prop="shopid" >
                        <el-select
                            v-model="settlementForm.shopid"
                            placeholder="选择门店"
                            popper-class="method-box"
                            class="input-w"
                        >
                            <el-option
                                v-for="item in store_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                                <div class="option-title">{{ item.name }}</div>
                                <div class="option-doc" v-if="item.address">
                                    地址：{{ item.address }}
                                </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关联云店" prop="shopid_yd" v-if="yun_show_list && yun_show_list.length" >
                        <el-select
                            v-model="settlementForm.shopid_yd"
                            placeholder="选择关联云店"
                            popper-class="method-box"
                            class="input-w"
                            clearable
                        >
                            <el-option
                                v-for="item in yun_show_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                                <div class="option-title">{{ item.name }}</div>
                                <div class="option-doc" v-if="item.district">
                                    地址：{{ item.district }}
                                </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务时间">
                        <el-date-picker
                            v-model="settlementForm.atime_txt"
                            type="datetime"
                            placeholder="选择业务时间"
                            class="input-w"
                            format="yyyy-MM-dd HH:mm"
                            value-format="yyyy-MM-dd HH:mm"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="经手人">
                        <el-select
                            v-model="settlementForm.uid_cp"
                            class="input-w"
                        >
                            <el-option
                                v-for="item in ucp_list"
                                :key="item.uid"
                                :label="item.name"
                                :value="item.uid"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input
                            type="textarea"
                            v-model="settlementForm.txt"
                            placeholder="添加详情,200字以内"
                            show-word-limit
                            class="input-w"
                        ></el-input>
                    </el-form-item>
                    <el-form-item class="mb-none">
                        <el-checkbox
                            v-model="settlementForm.isopen"
                            true-label="1"
                            false-label="'2'"
                            >对客户是否可见</el-checkbox
                        >
                    </el-form-item>
                    <el-form-item>
                        <addPhoto
                            ref="AddPhoto"
                            @uploadAavatar="uploadAavatar"
                            @deiimgFun="deiimgFun"
                        ></addPhoto>
                    </el-form-item>
                </el-form>
            </div>
            <div class="but-box">
                <div class="sett-info">
                    <div class="info-num">
                        <div class="num-txt">
                            <span>应收:</span><span>{{ cartInfo.amount }}</span
                            ><span class="discount" v-if="cartInfo.discount > 0"
                                >(优惠{{ cartInfo.discount }})</span
                            >
                        </div>
                        <div class="num-txt">
                            <span>实收:</span>
                            <span>{{
                                settlementForm.amount_receive || "0"
                            }}</span>
                        </div>
                    </div>
                </div>
                <div class="settlement-but">
                    <div class="but more" @click="is_more = !is_more">
                        <i class="el-icon-more"></i>
                    </div>
                    <div class="operation-box" v-show="is_more">
                        <div class="but more" @click="modifyDiscount">
                            <span>整单折扣</span>
                        </div>
                        <div class="but more" @click="preferentialErasure">
                            <span>优惠抹零</span>
                        </div>
                        <div class="but more" @click="saveDraft">
                            <span>存草稿单</span>
                        </div>
                        <div class="but more" @click="abandonBilling">
                            <span>放弃开单</span>
                        </div>
                    </div>
                    <div class="but avt" @click="completeFun">
                        <span>完成</span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 选择客户 -->
        <popCustomerSelect
            ref="popCustomerSelect"
            @getCustomerData="getCustomerData"
        ></popCustomerSelect>
        <!-- 图片裁剪 -->
        <imageCropper
            ref="imageCropper"
            :src="editUrl"
            @confirm="confirm"
            @cancel="cancel"
        >
        </imageCropper>
    </div>
</template>

<script>
import popCustomerSelect from "./popCustomerSelect.vue";
import config from "@/js/conf/Config.js";
import addPhoto from "@/components/comm/AddPhoto.vue";
import staticConst from "@/js/const/StaticConst.js";
import imageCropper from "@/components/comm/ImageCropper.vue";

export default {
    name: "settlementPay",
    components: { popCustomerSelect, addPhoto, imageCropper },
    props: ["page_i"],
    data() {
        return {
            orderClass: 1,
            is_more: true,
            customerInfo: {},
            editUrl: "",
            is_money: false,
            pay_ls: [],
            cartInfo: {},
            settlementData: {},
            settlementForm: {
                amount_receive: "",
                payid: "",
                shopid: "",
                atime_txt: "",
                txt: "",
                isopen: "2",
                txt_imgs: [],
                uid_cp: "",
                shopid_yd: "",
            },
            store_list: [],
            yun_show_list: [],
            ucp_list: [],
            rules: {
                amount_receive: [
                    {
                        required: true,
                        message: "请输入实收金额",
                        trigger: "blur",
                    },
                    {
                        pattern: /^\d+(.\d{1,2})?$/,
                        message: "请输入数字，支持俩位小数点",
                        trigger: "blur",
                    },
                ],
                payid: [
                    {
                        required: true,
                        message: "请选择付款方式",
                        trigger: "change",
                    },
                ],
                shopid: [
                    {
                        required: true,
                        message: "请选择门店",
                        trigger: "change",
                    },
                ],
            },
        };
    },
    methods: {
        async initData(data) {
            // this.getYunShopLs(); // 获取云店
            this.emptyData();
            await this.getsettlementInfo();
            await this.getStoreList();
            await this.getUcpList();
            this.customerInfo = data.customerInfo;
        },
        
        backFun() {
            this.$emit("backFun");
        },
        completeFun() {
            this.$refs.settlementForm.validate(async (valid) => {
                if (valid) {
                    if (this.settlementData.customerid == 0) {
                        this.$msg({ title: "请选择客户" });
                        return;
                    }
                    let param = this.getformFun();

                    let url = config.YY_ORDER_ORDER_ADD;
                    let res = await this.$api({ url: url, data: param });
                    if (res.status == 1) {
                        if (this.settlementForm.payid === "wxntv") {
                            param.odid = res.data.odid;
                            param.paytype = this.settlementForm.payid;
                            this.$emit("successfulSettlement", param);
                        } else {
                            this.backFun();
                        }
                    }
                }
            });
        },
        setAddPhoto(dataimg = null) {
            this.$nextTick(() => {
                let data = {};
                data.type = staticConst.UPLOAD_ORDER_REMASK;
                data.list = [
                    {
                        url: "",
                        imgs: "",
                        isDel: false,
                    },
                ];
                if (dataimg) {
                    dataimg.map((v) => {
                        data.list.unshift(v);
                    });
                    if (data.list.length > 9) {
                        data.list.splice(data.list.length - 1, 1);
                    }
                }
                this.$refs.AddPhoto.initPhotoData(data);
            });
        },
        // 获取经手人
        async getUcpList() {
            let param = {
                md: "yy",
                ch: "1",
            };
            let url = config.UCP_LS;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.ucp_list = res.data;
            }
        },
        // async getYunShopLs () {

        //     let url = config.YUN_SHOP_LS;
        //     let res = await this.$api({ url: url, data: {} });
        //     if (res.status == 1 && res.data) {
        //         this.yun_show_list = res.data;
        //     }
        // },
        // 获取门店列表
        async getStoreList() {
            let param = {
                ismy: "1",
                uid: this.cartInfo.uid,
            };
            let url = config.SHOP_LS;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1 && res.data) {
                this.store_list = res.data;
                if (res.data.length != 1) return false;
                this.settlementForm.shopid = res.data[0].id;
            }
        },
        // 获取结算信息
        async getsettlementInfo() {
            let param = {};
            let url = config.YY_ORDER_GD_ORDER_CHECKOUT;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.settlementData = res.data;
                this.is_money = false;
                this.cartInfo = res.data.cart_info;
                this.settlementForm.amount_receive = res.data.cart_info.amount;
                this.settlementForm.uid_cp = res.data.cart_info.uid;
                this.pay_ls = res.data.pay_ls || [];
                this.yun_show_list = res.data.shop_yun_ls;
                // this.settlementForm.shopid_yd
                if (this.yun_show_list.length  == 1) {
                    this.settlementForm.shopid_yd = res.data.shop_yun_ls[0].id
                }
                if (res.data.pay_ls_sys) {
                    res.data.pay_ls_sys.map((v) => {
                        v.id = v.paytype;
                        this.pay_ls.unshift(v);
                    });
                }
                if (res.data.cart_info.etime) {
                    this.settlementForm.atime_txt = this.getYMDHMS(
                        res.data.cart_info.etime
                    );
                }
                // 获取草稿信息{}
                if (res.data.init_info) {
                    this.settlementForm.payid =
                        res.data.init_info.payid > 0
                            ? res.data.init_info.payid
                            : "";

                    this.settlementForm.shopid =
                        res.data.init_info.shopid > 0
                            ? res.data.init_info.shopid
                            : "";

                    this.settlementForm.uid_cp =
                        res.data.init_info.uid_cp || "";

                    if (res.data.init_info.txt_ls) {
                        this.settlementForm.txt =
                            res.data.init_info.txt_ls[0].txt || "";
                        this.settlementForm.isopen =
                            String(res.data.init_info.txt_ls[0].isopen) || "";
                        if (res.data.init_info.txt_ls[0].imgs) {
                            let dataimg = [];
                            res.data.init_info.txt_ls[0].imgs.map((v, i) => {
                                this.settlementForm.txt_imgs.push({
                                    index: i,
                                    name: v.img_0,
                                });
                                dataimg.push({
                                    url: v.img_b,
                                    imgs: v.img_s,
                                    isDel: false,
                                    index:
                                        res.data.init_info.txt_ls[0].imgs
                                            .length -
                                        (i + 1),
                                });
                            });
                            this.setAddPhoto(dataimg);
                        } else {
                            this.setAddPhoto();
                        }
                    } else {
                        this.setAddPhoto();
                    }
                } else {
                    this.setAddPhoto();
                }
            }
        },
        // 选择客户
        async getCustomerData(data) {
            let param = { allCount: 0.0, customerid: data.id, totalMoney: 0.0 };
            let url = config.YY_ORDER_CART_SAVE;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.customerInfo = data;
                this.getsettlementInfo();
            }
        },
        modifyDiscount() {
            this.$prompt("输入折扣百分比", "整单折扣", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputPattern: /^(?:0|[1-9][0-9]?|100)(\.[0-9]{0,2})?$/,
                inputErrorMessage: "请输入0-100的数字，可包含俩位小数点",
            })
                .then(async ({ value }) => {
                    if (value > 100) {
                        this.$msg({ title: "折扣不能大于100" });
                        return;
                    }
                    let param = {
                        amount: this.cartInfo.amount_totle,
                        discount_r: value,
                        zero: 0,
                    };
                    this.countFun(param);
                })
                .catch(() => {});
        },
        preferentialErasure() {
            this.$prompt("输入抹零后的价格", "优惠抹零", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputPattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
                inputErrorMessage: "请输入数字且大于0，可包含俩位小数点",
            })
                .then(async ({ value }) => {
                    if (
                        Number(value) > Number(this.settlementData.amount_totle)
                    ) {
                        this.$msg({ title: "抹零后的价格不能超过订单原价" });
                        return;
                    }
                    let param = {
                        amount: this.cartInfo.amount_totle,
                        discount_r: 0,
                        zero: value,
                    };
                    this.countFun(param);
                })
                .catch(() => {});
        },
        saveDraft() {
            this.$confirm("您确定要把当前单据存入草稿单?", "存草稿单", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            })
                .then(async () => {
                    let param = this.getformFun();
                    param.backup = "1";
                    let url = config.YY_ORDER_ORDER_ADD;
                    let res = await this.$api({ url: url, data: param });
                    if (res.status == 1) {
                        this.backFun();
                    }
                })
                .catch(() => {});
        },
        abandonBilling() {
            this.$confirm("您确定放弃开单吗?", "放弃开单", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    let param = {
                        empty: "1",
                    };
                    let url = config.YY_ORDER_CART_SAVE;
                    let res = await this.$api({ url: url, data: param });
                    if (res.status == 1) {
                        this.backFun();
                    }
                })
                .catch(() => {});
        },

        // 操作价格变动的方法
        async countFun(param) {
            let url = config.YY_ORDER_ORDER_COUNT;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.cartInfo.discount_r = parseFloat(res.data.discount_r);
                this.cartInfo.discount = res.data.discount;
                this.cartInfo.amount = res.data.amount;
                this.settlementForm.amount_receive = res.data.amount;
            }
        },
        // 打开客户列表
        selectCustom() {
            this.$refs.popCustomerSelect.initData();
        },
        /*****上传图片成功*****/
        uploadPicSuccess(index, name) {
            this.settlementForm.txt_imgs.push({ index, name });
        },
        /*******上传图片*******/
        uploadAavatar(data) {
            this.editUrl = data.url;
        },
        // 删除图片
        deiimgFun(data) {
            this.settlementForm.txt_imgs.map((v, i) => {
                if (data.index == v.index) {
                    this.settlementForm.txt_imgs.splice(i, 1);
                }
            });
        },
        /*****确认编辑图片****/
        confirm(data) {
            this.$refs.AddPhoto.confirm(data, this.uploadPicSuccess);
        },
        /****取消上传****/
        cancel() {
            this.$refs.AddPhoto.cancel();
        },
        getYMDHMS(timestamp) {
            let time = new Date(timestamp * 1000);
            let year = time.getFullYear();
            const month = (time.getMonth() + 1).toString().padStart(2, "0");
            const date = time.getDate().toString().padStart(2, "0");
            const hours = time.getHours().toString().padStart(2, "0");
            const minute = time.getMinutes().toString().padStart(2, "0");

            return year + "-" + month + "-" + date + " " + hours + ":" + minute;
        },
        emptyData() {
            this.settlementForm = {
                amount_receive: "",
                payid: "",
                shopid: "",
                atime_txt: "",
                txt: "",
                isopen: "2",
                txt_imgs: [],
                uid_cp: "",
            };
        },
        getformFun() {
            const param = {
                amount: this.cartInfo.amount,
                amount_receive: this.settlementForm.amount_receive,
                amount_shipp: "",
                amount_zero: this.cartInfo.discount,
                atime_txt: this.settlementForm.atime_txt,
                discount_r: this.cartInfo.discount_r,
                ispay_end: "0",
                isprint: "2",
                shipp_info: {
                    address: this.settlementData.address_info.address,
                    addressee: this.settlementData.address_info.addressee,
                    area: this.settlementData.address_info.area,
                    cellphone: this.settlementData.address_info.cellphone,
                    city: this.settlementData.address_info.city,
                    district: this.settlementData.address_info.district,
                    province: this.settlementData.address_info.province,
                },
                shipp_type: "",
                shopid: this.settlementForm.shopid,
                shopid_yd: this.settlementForm.shopid_yd,
                uid_cp: this.settlementForm.uid_cp,
                txt: this.settlementForm.txt,
            };

            if (this.settlementForm.isopen == 1) {
                param.isopen = this.settlementForm.isopen;
            }
            if (this.settlementForm.txt_imgs.length > 0) {
                param.txt_imgs = [];
                this.settlementForm.txt_imgs.map((v) => {
                    param.txt_imgs.push(v.name);
                });
            }
            if (this.is_money) {
                param.money = this.settlementData.money;
            }
            if (
                this.settlementForm.payid != "wxntv" &&
                this.settlementForm.amount_receive > 0
            ) {
                param.payid = this.settlementForm.payid;
            }


            return param;
        },
    },
};
</script>

<style lang="scss" scoped>
.settlement-pay {
    height: 100vh;
    // margin-left: 72px;
    background-color: #fff;
    position: relative;
    .header-box {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px #e8dcdc solid;
        padding: 0 10px;
        padding-right: 20px;
        display: flex;
        .header-left {
            display: flex;
            .back {
                font-size: 20px;
                margin-right: 10px;
                cursor: pointer;
            }
            .title {
                font-size: 18px;
                padding-top: 3px;
            }
        }
    }
    .settlement-info {
        height: calc(100% - 130px);
        padding: 10px;
        overflow: auto;
        .settlement-form {
            .order-box {
                width: 300px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .order-pic {
                font-size: 16px;
                font-weight: bold;
            }
            .discount {
                font-size: 12px;
                color: #f14f4f;
                margin-left: 10px;
            }
            .input-w {
                width: 300px;
            }
            .mb-none {
                margin-bottom: 0;
            }
        }
        .choice-box {
            border: 1px #e8dcdc solid;
            margin-bottom: 20px;
            padding: 10px;
            .choice-info {
                display: flex;
                align-items: center;
                justify-content: space-between;
                .choice-info-left {
                    display: flex;
                    align-items: center;
                    .img-box {
                        width: 80px;
                        height: 80px;
                        border-radius: 50%;
                        overflow: hidden;
                        margin-right: 10px;
                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                        }
                    }
                    .choice-content {
                        font-size: 14px;
                        .title {
                            span {
                                margin-right: 10px;
                            }
                        }
                    }
                }
                .choice-info-right {
                    display: flex;
                    align-items: center;
                }
            }
        }
        .but-box {
            position: absolute;
            left: 0;
            bottom: 0;
            height: 60px;
            width: 100%;
            border-top: 1px #e8dcdc solid;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .sett-info {
                font-size: 12px;
                display: flex;
                margin-left: 10px;
                .info-num {
                    margin-right: 30px;

                    .num-txt {
                        .discount {
                            color: #f14f4f;
                        }
                        &.checked {
                            padding-left: 10px;
                            cursor: pointer;
                        }
                        span {
                            margin-right: 10px;
                        }

                        .num {
                            color: #fb6868;
                        }
                        .all-txt {
                            margin-left: 10px;
                        }
                    }
                }
            }
            .settlement-but {
                height: 100%;
                display: flex;
                .operation-box {
                    display: flex;
                }
                .but {
                    height: 100%;
                    padding: 0 20px;
                    font-size: 16px;
                    display: flex;
                    align-items: center;
                    cursor: pointer;
                    &.more {
                        border-left: 1px #e8dcdc solid;
                        &:hover {
                            opacity: 0.8;
                            background: #ecebeb;
                        }
                    }

                    &.avt {
                        padding: 0 40px;
                        background: #3388ff;
                        color: #fff;
                        &:hover {
                            background: #5498f7;
                        }
                    }
                    &.ext {
                        background: #3388ff;
                        padding: 0 40px;
                        color: #fff;
                        &:hover {
                            opacity: 0.8;
                        }
                    }
                    &.del {
                        background: #fa4848;
                        color: #fff;
                        padding: 0 40px;
                        &:hover {
                            opacity: 0.8;
                        }
                    }
                }
            }
        }
    }
}
</style>